<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>WebSocket Demo</title>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<input id="msg" type="text" />
<button onclick="send()">发送消息</button>
<hr>

<button onclick="reminder()">提醒发货</button>
<audio src="reminder.mp3" id="reminderAudio"></audio>

</body>

<script>
  // 连接WebSocket服务器
  const clientId = Math.random().toString(36).substr(2);
  const websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);

  // 监听连接建立成功
  websocket.onopen = function(){
    console.log("WebSocket连接成功......");
  }

  // 监听收到服务端消息
  websocket.onmessage = function(event){
    console.log(event.data);

    const msg = JSON.parse(event.data)
    console.log(msg)
    /**
     * 判断消息的类型
     */
    if (msg.type == 1){
        // 语音播报
        document.getElementById('reminderAudio').currentTime=0
        document.getElementById('reminderAudio').play();

       // 弹框提醒
       alert('客户催单啦，订单号：' + msg.orderNumber + '，请及时处理！')
    }

  }

  // 发送消息
  function send(){
    websocket.send(document.getElementById('msg').value);
  }

  // 监听窗口关闭事件，当窗口关闭时主动去关闭websocket连接
  window.onbeforeunload = function(){
    websocket.close();
  }

  function reminder(){
    $.ajax({
      url: "http://localhost:8080/orders/reminder",
      type: "get",
      data: {
        "orderId": 1001
      },
      dataType:'json',
      success: function (data) {
        console.log(data);
      }
    });

  }
</script>
</html>
